﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Uaf.Core
{
	public class Container : IContainer
	{
		private class ServiceInfo
		{
			public Type Type { get; set; }
			public string Name { get; set; }
			public object Instance { get; set; }
		}

		private List<ServiceInfo> _services = new List<ServiceInfo>();

		public void Register<T>(T instance)
		{
			RegisterInternal<T>(instance, null);
		}

		public void Register<T>(T instance, string name)
		{
			if (name == null)
				throw new ArgumentNullException("name");
			RegisterInternal<T>(instance, name);
		}

		private void RegisterInternal<T>(T instance, string name)
		{
			if (instance == null)
				throw new ArgumentNullException("instance");

			var type = typeof(T);
			_services.RemoveAll(info => info.Type == type && info.Name == name);
			_services.Add(new ServiceInfo() { Type = type, Name = name, Instance = instance });
		}

		public T Resolve<T>()
		{
			return Resolve<T>(null);
		}

		public T Resolve<T>(string name)
		{
			var type = typeof(T);
			var info = _services.FirstOrDefault(p => p.Type == type && p.Name == name);
			return info != null ? (T)info.Instance : default(T);
		}

		public IEnumerable<T> ResolveAll<T>()
		{
			var type = typeof(T);
			return _services.Where(p => p.Type == type).Select(p => p.Instance).Cast<T>();
		}
	}
}
